<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {

	public function index()
	{
		$islogin = $this->session->userdata('islogin');
		if ($islogin === true){
			redirect(BASEWEBSITE);
		}
		
		$data = array(
			'version' => 1,
			'err_msg' => ''
		);
		
		if ($this->input->post()){
			$vcode_session = $this->encrypt->decode($this->session->flashdata('vcode_tmp'));
			
			$user = getdata($this->input->post('username'));
			$pass = getdata($this->input->post('password'));
			$vcode = getdata($this->input->post('vcode'));
			
			if (empty($user) || empty($pass) || empty($vcode)){
				$data['err_msg'] = '信息为空';
				$this->load->view('login', $data);
				return true;
			}
			
			if ($vcode != $vcode_session){
				$data['err_msg'] = '验证码错误';
				$this->load->view('login', $data);
				return true;
			}
			
			$this->load->model('Login_model', 'Mlogin', true);
			$re_user = $this->Mlogin->check_pass($user);
			if (empty($re_user)){
				$data['err_msg'] = '用户不存在';
				$this->load->view('login', $data);
				return true;
			}
			
			if (md5($pass) != $re_user['pass']){
				$data['err_msg'] = '密码错误';
				$this->load->view('login', $data);
				return true;
			}
			
			$user_info = array(
				'userid'	=> $re_user['id'],
				'username'  => $re_user['user'],
				'nickname'  => $re_user['nickname'],
				'islogin'	=> true
			);
			$this->session->set_userdata($user_info);
			redirect(BASEWEBSITE);
		}
		
		$this->load->view('login', $data);
		
	}
	
	public function logout(){
		$user_info = array('userid' => '', 'username' => '', 'nickname' => '', 'islogin' => '');
		$this->session->unset_userdata($user_info);
		redirect(BASEWEBSITE . 'login');
	}
}
